package cn.iune.erp.customer;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

import cn.iune.erp.setting.ISettingService;


@Transactional
@Service
public class MemberBalanceServiceImpl implements IMemberBalanceService {
	
	@Autowired
//	@Resource(name="IMemberBalanceDao")
	private IMemberBalanceDao dao;
	
	@Autowired
	private ISettingService appPreloading;

	
	@Override
	public MemberBalance update(MemberBalance obj){
		return dao.update(obj);
	}

	
	/* (non-Javadoc)
	 * @see com.iune.erp.baseinfo.aaa#getAll()
	 */
	@Override
	public List<MemberBalance> getAll(){
		return dao.getAll();
	}
	
	@Override
//	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<MemberBalance> getList(String customerID) {
		return dao.getList(customerID);
	}

	
	/* (non-Javadoc)
	 * @see com.iune.erp.baseinfo.aaa#getByID(java.lang.String)
	 */
	@Override
	public MemberBalance getByID(String fID) {
		return dao.getByID(fID);
	}
	
	@Override
	public MemberBalance getByNo(String balanceNo, String enterpriseNo) {
		return dao.getByNo(balanceNo, enterpriseNo);
	}
		
	@Override
	public MemberBalance getByOriginNo(String customerID, String originNo) {
		return dao.getByOriginNo(customerID, originNo);
	}

	/* (non-Javadoc)
	 * @see com.iune.erp.baseinfo.aaa#delete(java.lang.String)
	 */
	@Transactional
	@Override
	public void delete(String fID) {
		dao.delete(fID);
	}


	/* (non-Javadoc)
	 * @see com.iune.erp.baseinfo.aaa#save(com.alibaba.fastjson.JSONObject)
	 */
	@Transactional
	@Override
	public JSONObject save(JSONObject object) throws ParseException  {
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject data = new JSONObject();
		data.put("concept", table.getTableName());
		JSONArray rows = new JSONArray();
		List<String> idsNew = new ArrayList<String>();
		List<String> idsDel = new ArrayList<String>();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			MemberBalance obj = JSON.toJavaObject(javaObject, MemberBalance.class);
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
				idsNew.add(obj.getfID());
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getfID());
				idsDel.add(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				MemberBalance objNew = dao.update(obj);
				//返回+1后的version到前台BizData中进行刷新，使得前台的version与后台的一致。
				///////////////////////////////////////////////////////////////////////
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
				//////////////////////////////////////////////////////////////////////
			}
		}
		
		data.put("rows", rows);
		data.put("idsNew", idsNew);
		data.put("idsDel", idsDel);
		
		return data;
	}
	


	@Override
	public MemberBalance insert(
			String origin,
			String originName,
			String originNo,

			String balanceNo, String systemCode, String billType, String billTypeName, String dealObject, String dealObjectLabel, String customerID, String customerNo, String shortName, String customerName
			, String remark, BigDecimal balance, String handling, String handlingLabel
			, String cUsercode 
			, String cUsername
			, String userId 
			, String enterpriseNo
			, String enterpriseName 
			) {
		
		MemberBalance obj = new MemberBalance();
		obj.setfID(Utils.getUUID());

		obj.setSystemCode(systemCode);
		obj.setBillType(billType);
		obj.setBillTypeName(billTypeName);
		obj.setOrderDate(Utils.getCurrentDate());
		obj.setState("active");
		obj.setStatus("open");
		
		obj.setOrigin(origin);
		obj.setOriginName(originName);
		obj.setOriginNo(originNo);
		
		obj.setBalanceNo(balanceNo);
		
		obj.setDealObject(dealObject);
		obj.setDealObjectLabel(dealObjectLabel);
		obj.setCustomerID(customerID);
		obj.setCustomerNo(customerNo);
		obj.setShortName(shortName);
		obj.setCustomerName(customerName);
		
		obj.setRemark(remark);
		obj.setBalance(balance);
		obj.setActualAmount(BigDecimal.ZERO);
		obj.setHandling(handling);
		obj.setHandlingLabel(handlingLabel);
		//obj.setComments(comments);
		
		obj.setcUsercode(cUsercode);
		obj.setcUsername(cUsername);
		obj.setcDatetime(Utils.getCurrentDateTime());
		obj.setUserId(userId);
		obj.setEnterpriseNo(enterpriseNo);
		obj.setEnterpriseName(enterpriseName);
		
		dao.insert(obj);
		
		return obj;
	}

	//会员充值
	@Override
	public MemberBalance yeczInsert(
			String origin,
			String originName,
			String originNo,
			String dealObject, String dealObjectLabel, String customerID, String customerNo, String shortName, String customerName
			, String remark, BigDecimal balance
			, String cUsercode 
			, String cUsername
			, String userId 
			, String enterpriseNo
			, String enterpriseName 
			) {
		
		MemberBalance obj = new MemberBalance();
		obj.setfID(Utils.getUUID());
		
		String billType = "YECZ";
		Map<String,Object> map = appPreloading.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
		String systemCode = (String) map.get("systemCode");
//		int flowType = (int) map.get("flowType");
//		String revOpay = (String) map.get("revOpay");
//		int direction = (int) map.get("direction");
//		String costingCode = (String) map.get("costingCode");
//		String autoCode = (String) map.get("autoCode");
//		String origin = (String) map.get("origin");
//		String originName = (String) map.get("originName");
		String billNo = (String) map.get("billNo");
		
		String handling = "unpaid";
		String handlingLabel = "待付款";

		return this.insert(origin,originName,originNo,billNo, systemCode, billType, billTypeName, dealObject, dealObjectLabel, customerID, customerNo, shortName, customerName, remark, balance, handling, handlingLabel, cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
	}

	//会员消费
	@Override
	public MemberBalance yexfInsert(
			String origin,
			String originName,
			String originNo,
			String dealObject, String dealObjectLabel, String customerID, String customerNo, String shortName, String customerName
			, String remark, BigDecimal balance
			, String cUsercode 
			, String cUsername
			, String userId 
			, String enterpriseNo
			, String enterpriseName 
			) {
		
		MemberBalance obj = new MemberBalance();
		obj.setfID(Utils.getUUID());
		
		String billType = "YEXF";
		Map<String,Object> map = appPreloading.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
		String systemCode = (String) map.get("systemCode");
//		int flowType = (int) map.get("flowType");
//		String revOpay = (String) map.get("revOpay");
//		int direction = (int) map.get("direction");
//		String costingCode = (String) map.get("costingCode");
//		String autoCode = (String) map.get("autoCode");
//		String origin = (String) map.get("origin");
//		String originName = (String) map.get("originName");
		String billNo = (String) map.get("billNo");
		
		String handling = "unclear";
		String handlingLabel = "待核销";

		return this.insert(origin,originName,originNo,billNo, systemCode, billType, billTypeName, dealObject, dealObjectLabel, customerID, customerNo, shortName, customerName, remark, balance, handling, handlingLabel, cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
	}
	
	@Override
	public MemberBalance updateHandling(String customerID, String originNo, 
			BigDecimal actualAmount,
			String handling, String handlingLabel
			) {
		MemberBalance obj = dao.getByOriginNo(customerID, originNo);
		if(obj==null) return null;
		
		obj.setActualAmount(actualAmount);
		obj.setHandling(handling);
		obj.setHandlingLabel(handlingLabel);
		
		return dao.update(obj);
	}
	
	@Override
	public JSONObject newData(JSONObject data) {
		return dao.create(data);
	}
	
	@Override
	public JSONObject deleteData(JSONObject param) {
		//System.out.println("fileFactoryCreate.param-->>"+param.toJSONString());
		JSONArray ids = param.getJSONArray("ids");
		for(int i=0;i<ids.size();i++){
			String id = ids.getString(i);
			//这里可以增加是否可删除的判断
			
			dao.delete(id);
		}

		JSONObject data = new JSONObject();
		data.put("ids", ids);
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", data);
		
		return json;
	}

	/*
	在@Transaction注解中定义noRollbackFor和RollbackFor指定某种异常是否回滚。 
	@Transactional(noRollbackFor=RuntimeException.class) 
	@Transactional(RollbackFor=Exception.class) 
	*/
	@Transactional
	@Override
	public JSONObject saveData(JSONObject param) {
		//Spring的事务管理默认只对出现运行期异常(java.lang.RuntimeException及其子类)进行回滚。 
		//如果一个方法抛出Exception或者Checked异常，Spring事务管理默认不进行回滚。 
		// JSON转换Table
		//System.out.println(object);
		JSONObject data;
		try {
			data = this.save(param);
					
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", data);
			
			return json;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			
			return json;
		} 
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.baseinfo.aaa#queryJDBC(com.alibaba.fastjson.JSONObject)
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@Override
	public JSONObject queryData(JSONObject param){
		//在此层面（ServiceImpl）统一处理异常，此层面直接被controller调用，面对BizData
		
		try {
			JSONObject jsonTable = dao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}

	@Override
	public JSONObject validData(JSONObject param) {
		// TODO Auto-generated method stub
		return null;
	}

}
